<route lang="json">
{
    "name": "manage",
    "meta": {
        "title": "控制台",
        "requiresAuth": true
    }
}
</route>

<script setup lang="ts">
import { BarChart, LineChart } from 'echarts/charts'
import {
  DatasetComponent,
  GridComponent,
  LegendComponent,
  TitleComponent,
  TooltipComponent,
  TransformComponent,
} from 'echarts/components'
import * as echarts from 'echarts/core'
import { LabelLayout, UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { onMounted, onUnmounted, ref } from 'vue'
import { getKData, getSimpleData } from '~/api/data'

// 定义类型
interface StatisticsItem {
  title: string
  value: string | number
  icon: string
  color: string
}

interface KLineData {
  x: string[]
  val: number[][]
}

interface SimpleDataItem {
  x: string
  val: number
}

interface OrderItem {
  id: string
  customer: string
  amount: string
  status: 'success' | 'warning' | 'info'
  time: string
}

interface NotificationItem {
  title: string
  content: string
  time: string
  type: 'success' | 'warning' | 'info' | 'error'
}

// 注册必需的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LegendComponent,
  LineChart,
  BarChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer,
])

// 统计数据
const statisticsData = ref<StatisticsItem[]>([
  { title: '今日订单', value: 213, icon: 'ShoppingCart', color: '#409EFF' },
  { title: '今日销售额', value: '¥8,592', icon: 'Money', color: '#67C23A' },
  { title: '新增用户', value: 47, icon: 'User', color: '#E6A23C' },
  { title: '商品总数', value: 1293, icon: 'Goods', color: '#F56C6C' },
])

// 图表实例
const lineChartRef = ref<HTMLElement | null>(null)
const barChartRef = ref<HTMLElement | null>(null)
let lineChart: echarts.ECharts | null = null
let barChart: echarts.ECharts | null = null

// 图表数据
const kLineData = ref<KLineData>({
  x: [],
  val: [],
})
const simpleData = ref<SimpleDataItem[]>([])

// 订单数据
const recentOrders = ref<OrderItem[]>([
  { id: '1001', customer: '张三', amount: '¥1,200', status: 'success', time: '2023-08-11 10:23' },
  { id: '1002', customer: '李四', amount: '¥890', status: 'warning', time: '2023-08-11 09:12' },
  { id: '1003', customer: '王五', amount: '¥2,530', status: 'success', time: '2023-08-10 18:45' },
  { id: '1004', customer: '赵六', amount: '¥720', status: 'info', time: '2023-08-10 15:30' },
])

// 通知数据
const notifications = ref<NotificationItem[]>([
  { title: '系统更新', content: '系统将于今晚22:00-23:00进行例行维护更新', time: '10分钟前', type: 'warning' },
  { title: '新功能上线', content: '商品管理模块新增批量导入功能', time: '2小时前', type: 'success' },
  { title: '安全提醒', content: '请定期修改您的登录密码，确保账号安全', time: '1天前', type: 'info' },
  { title: '活动预告', content: '618大促活动即将开始，请做好商品库存准备', time: '2天前', type: 'info' },
])

// 状态映射
const statusMap: Record<string, string> = {
  success: '已完成',
  warning: '处理中',
  info: '待付款',
}

// 加载数据
async function loadData() {
  try {
    // 先使用模拟数据初始化
    kLineData.value = {
      x: ['2021-11-15', '2021-11-16', '2021-11-17', '2021-11-18'],
      val: [
        [20, 34, 10, 38],
        [40, 35, 30, 50],
        [31, 38, 33, 44],
        [38, 15, 5, 42],
      ],
    }

    simpleData.value = [
      { x: '星期一', val: 150 },
      { x: '星期二', val: 230 },
      { x: '星期三', val: 224 },
      { x: '星期四', val: 218 },
      { x: '星期五', val: 135 },
      { x: '星期六', val: 147 },
      { x: '星期日', val: 260 },
    ]

    // 初始化图表
    initCharts()

    // 尝试从API获取数据
    try {
      // 获取K线图数据
      const kData = await getKData()
      if (kData?.data?.x && kData?.data?.val) {
        kLineData.value = kData.data
      }

      // 获取简单图表数据
      const sData = await getSimpleData()
      if (sData?.data && Array.isArray(sData.data)) {
        simpleData.value = sData.data
      }

      // 更新图表
      updateCharts()
    }
    catch (apiError) {
      console.error('API数据加载失败，使用模拟数据:', apiError)
    }
  }
  catch (error) {
    console.error('加载数据失败:', error)
  }
}

// 初始化图表
function initCharts() {
  // 初始化折线图
  if (lineChartRef.value) {
    // 如果已经初始化过，先销毁
    if (lineChart) {
      lineChart.dispose()
    }
    lineChart = echarts.init(lineChartRef.value)
    const series = kLineData.value.val.map((item, index) => {
      return {
        name: `数据${index + 1}`,
        type: 'line',
        data: item,
        smooth: true,
      }
    })

    lineChart.setOption({
      title: {
        text: '多维度数据趋势',
        left: 'center',
      },
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: series.map(item => item.name),
        bottom: 0,
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: '15%',
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: kLineData.value.x,
      },
      yAxis: {
        type: 'value',
      },
      series,
    })
  }

  // 初始化柱状图
  if (barChartRef.value) {
    // 如果已经初始化过，先销毁
    if (barChart) {
      barChart.dispose()
    }
    barChart = echarts.init(barChartRef.value)
    barChart.setOption({
      title: {
        text: '一周销售数据',
        left: 'center',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '15%',
      },
      xAxis: {
        type: 'category',
        data: simpleData.value.map(item => item.x),
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: '销售额',
          type: 'bar',
          data: simpleData.value.map(item => item.val),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' },
            ]),
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#2378f7' },
                { offset: 0.7, color: '#2378f7' },
                { offset: 1, color: '#83bff6' },
              ]),
            },
          },
        },
      ],
    })
  }
}

// 窗口大小变化时重新调整图表大小
function handleResize() {
  lineChart?.resize()
  barChart?.resize()
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
  window.addEventListener('resize', handleResize)
})

// 更新图表数据
function updateCharts() {
  if (lineChart) {
    const series = kLineData.value.val.map((item, index) => {
      return {
        name: `数据${index + 1}`,
        type: 'line',
        data: item,
        smooth: true,
      }
    })

    lineChart.setOption({
      xAxis: {
        data: kLineData.value.x,
      },
      legend: {
        data: series.map(item => item.name),
      },
      series,
    })
  }

  if (barChart) {
    barChart.setOption({
      xAxis: {
        data: simpleData.value.map(item => item.x),
      },
      series: [
        {
          data: simpleData.value.map(item => item.val),
        },
      ],
    })
  }
}

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (lineChart) {
    lineChart.dispose()
    lineChart = null
  }
  if (barChart) {
    barChart.dispose()
    barChart = null
  }
})
</script>

<template>
  <div class="dashboard-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-row">
      <el-col v-for="(item, index) in statisticsData" :key="index" :xs="24" :sm="12" :md="6" class="statistics-col">
        <el-card shadow="hover" class="statistics-card" :style="{ borderLeft: `4px solid ${item.color}` }">
          <div class="statistics-content">
            <div class="statistics-icon" :style="{ backgroundColor: `${item.color}20`, color: item.color }">
              <el-icon :size="24">
                <component :is="item.icon" />
              </el-icon>
            </div>
            <div class="statistics-info">
              <div class="statistics-title">
                {{ item.title }}
              </div>
              <div class="statistics-value">
                {{ item.value }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <div ref="lineChartRef" class="chart" />
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <div ref="barChartRef" class="chart" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近活动 -->
    <el-row :gutter="20" class="activity-row">
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="activity-card">
          <template #header>
            <div class="card-header">
              <span>最近订单</span>
              <el-button text>
                查看全部
              </el-button>
            </div>
          </template>
          <el-table :data="recentOrders" style="width: 100%">
            <el-table-column prop="id" label="订单号" width="100" />
            <el-table-column prop="customer" label="客户" width="100" />
            <el-table-column prop="amount" label="金额" width="100" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="scope.row.status">
                  {{ statusMap[scope.row.status] }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="time" label="时间" />
          </el-table>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="activity-card">
          <template #header>
            <div class="card-header">
              <span>系统通知</span>
              <el-button text>
                查看全部
              </el-button>
            </div>
          </template>
          <div class="notification-list">
            <div v-for="(item, index) in notifications" :key="index" class="notification-item">
              <el-alert
                :title="item.title"
                :description="item.content"
                :type="item.type"
                :closable="false"
                show-icon
              >
                <template #default>
                  <div class="notification-time">
                    {{ item.time }}
                  </div>
                </template>
              </el-alert>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped lang="scss">
.dashboard-container {
  padding: 20px;

  .statistics-row {
    margin-bottom: 20px;

    .statistics-col {
      margin-bottom: 20px;

      .statistics-card {
        height: 100px;

        .statistics-content {
          display: flex;
          align-items: center;
          height: 100%;

          .statistics-icon {
            width: 60px;
            height: 60px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 15px;
          }

          .statistics-info {
            flex: 1;

            .statistics-title {
              font-size: 14px;
              color: #909399;
              margin-bottom: 8px;
            }

            .statistics-value {
              font-size: 24px;
              font-weight: bold;
              color: #303133;
            }
          }
        }
      }
    }
  }

  .chart-row {
    margin-bottom: 20px;

    .chart-card {
      margin-bottom: 20px;

      .chart {
        height: 350px;
      }
    }
  }

  .activity-row {
    .activity-card {
      margin-bottom: 20px;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .notification-list {
        .notification-item {
          margin-bottom: 10px;

          .notification-time {
            font-size: 12px;
            color: #909399;
            margin-top: 5px;
            text-align: right;
          }
        }
      }
    }
  }
}
</style>
